﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mvc2Ng.Web.NgLib.Extensions.Attributes;

namespace Mvc2Ng.Web.UI.Controllers {
  public class AngularJsController : Controller {

    //[OutputCache(Duration = 3600)]
    public JavaScriptResult GetAngularControllers() {
      var methods = this.GetType().GetMethods().Where(m => m.GetCustomAttributes(typeof(NgControllerAttribute), true).OfType<NgControllerAttribute>().Any());
      var scripts = new List<string>();
      foreach (var methodInfo in methods) {
        var ac = methodInfo.GetCustomAttributes(typeof(NgControllerAttribute), true).OfType<NgControllerAttribute>().Single<NgControllerAttribute>();
        var path = ac.ControllerPath;
        if (!String.IsNullOrEmpty(path)) {
          path = HttpContext.Server.MapPath(path);
        }
        else {
          path = HttpContext.Server.MapPath(String.Format("~/Areas/{0}/Views/{1}/js/{2}.js", RouteData.Values["area"], RouteData.Values["controller"], methodInfo.Name.ToLower()));
        }
        if (System.IO.File.Exists(path)) {
          using (var file = System.IO.File.OpenText(path)) {
            scripts.Add(file.ReadToEnd());
            file.Close();
          }
        }
      }
      return JavaScript(String.Join("\n", scripts.ToArray()));
    }

  }
}